/*
 * Copyright 2018 Zhenjie Yan.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.swsc.xapp.utils;

import android.os.Environment;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import com.swsc.xapp.baseContent.MyApplication;
import com.swsc.xapp.offline.lhttpd.ApiException;
import com.serenegiant.MyApp;
import com.yanzhenjie.andserver.http.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.UUID;

/**
 * Created by Zhenjie Yan on 2018/6/9.
 */
public class FileUtils {

    /**
     * Create a random file based on mimeType.
     *
     * @param file file.
     * @return file object.
     */
    public static File createRandomFile(MultipartFile file) {
        String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(file.getContentType().toString());
        if (TextUtils.isEmpty(extension)) {
            extension = MimeTypeMap.getFileExtensionFromUrl(file.getFilename());
        }
        String uuid = UUID.randomUUID().toString();
        return new File(ConstantUils.DIR_BASE.concat("/temp/"), uuid + "." + extension);
    }

    public static void saveByRandomAccessFile(InputStream is, String destFilePath) {
        File newFile = new File(destFilePath);
        checkFileParentDir(newFile);
        BufferedInputStream inputStream = new BufferedInputStream(is);
        RandomAccessFile raFile = null;
        try {
            raFile = new RandomAccessFile(newFile, "rw");
            raFile.seek(raFile.length());
            byte[] buf = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buf)) != -1) {
                raFile.write(buf, 0, length);
            }
        } catch (FileNotFoundException e) {
            android.util.Log.e("保存文件", "文件不存在");
        } catch (IOException e) {
            android.util.Log.e("保存文件", e.getMessage());
        } finally {
            close(inputStream, null);
            close(raFile);
        }


    }

    public static void copyFileFromAsset(String fileName, String targetDir) {
        InputStream is = null;
        FileOutputStream os = null;
        try {
            is = ContextUtils.getCurApplication().getAssets().open(fileName);
            File targetFile = new File(targetDir.concat("/").concat(fileName));
            NativeJSUtils.checkFileParentDir(targetFile);
            if (targetFile.exists()) {
                android.util.Log.i("FlygoData: ", "文件已存在");
                return;
            }
            os = new FileOutputStream(targetFile);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(is, os);
        }
    }
    public static void copyFile(File oldFile, File newFile){
        if(null != oldFile && null != newFile){
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(oldFile);
                fos = new FileOutputStream(newFile);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fos.flush();
            } catch (FileNotFoundException e) {
                android.util.Log.i("复制文件: ", e.getMessage());
                return;
            } catch (IOException e) {
                android.util.Log.i("复制文件: ", e.getMessage());
                return;
            }finally {
                close(fis, fos);
            }
        }
    }

    public static String moveFile(String oldFilePath, String destDir) throws IOException {
        File oldFile = new File(oldFilePath);
        ApiException.isFalse(!oldFile.exists(), "旧文件不存在");
        String fileName = oldFile.getName();
        String newFileName = destDir.concat("/").concat(fileName);
        File newFile = new File(newFileName);
        checkFileParentDir(newFile);
        //BufferedInputStream bis = new BufferedInputStream(new FileInputStream(oldFile));
        copyFile(oldFile, newFile);
        oldFile.delete();
        return newFileName;
    }

    public static void copyFile(byte[] bytes, String newFilePath) throws IOException {
        File file = new File(newFilePath);
        checkFileParentDir(file);
        try(BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))){
            out.write(bytes);
            out.flush();
        }
    }

    public static void close(InputStream is, OutputStream os) {
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != os) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(RandomAccessFile randomAccessFile) {
        if (null != randomAccessFile) {
            try {
                randomAccessFile.close();
            } catch (IOException e) {
                android.util.Log.e("关闭文件", e.getMessage());
            }
        }
    }

    public static void checkFileParentDir(File file) {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
    }

    public static String getFileName(String path){
        File file = new File(path);
        return file.getName();
    }
    public static String getFileNameNonSuffix(String fileName){
        if(null != fileName){
            return fileName.split("\\.")[0];
        }
        return null;
    }
}